#include "JZRpcDataManager.h"
#include <QDataStream>
#include <QJsonDocument>

//JZRpcDataManager
JZRpcDataManager::JZRpcDataManager()
{        
}

JZRpcDataManager::~JZRpcDataManager() 
{
}

void JZRpcDataManager::newSession(int sessionId, QTcpSocket *socket)
{	
	m_sessionInfo[sessionId].socket = socket;	
}

void JZRpcDataManager::endSession(int sessionId)
{	
	m_sessionInfo.remove(sessionId);	
}

QTcpSocket *JZRpcDataManager::socket(int sessionId)
{
    return m_sessionInfo[sessionId].socket;
}

void JZRpcDataManager::recvPack(int sessionId)
{	
	QTcpSocket *socket = m_sessionInfo[sessionId].socket;	
    QByteArray buffer = socket->readAll();
    m_sessionInfo[sessionId].buffer.append(buffer);						
	parsePack(sessionId);
}

void JZRpcDataManager::recvData(int sessionId, QByteArray data)
{
	m_sessionInfo[sessionId].buffer.append(data);
	parsePack(sessionId);
}

QByteArray JZRpcDataManager::packData(const QJsonObject &pack)
{	
	QJsonDocument doc(pack);
    QByteArray ret = doc.toJson(QJsonDocument::Compact);
    ret.push_back('\n');
    return ret;
}

bool JZRpcDataManager::sendPack(int sessionId, const QJsonObject &pack)
{			
	QByteArray send_buffer = packData(pack);
	QTcpSocket *socket = m_sessionInfo[sessionId].socket;
	Q_ASSERT(socket);
        
    const char *ptr = send_buffer.data();
    int total_size = send_buffer.size();  
    int remain_size = send_buffer.size();    
    while(remain_size > 0)
    {
        int write_size = socket->write(ptr + total_size - remain_size, remain_size);    
        remain_size -= write_size;
        if(remain_size > 0)
            socket->waitForBytesWritten();
    }    
    return true;
}

QJsonObject JZRpcDataManager::takePack(int sessionId)
{
    Q_ASSERT(m_sessionInfo.contains(sessionId));

	QJsonObject pack;
	QVector<QJsonObject> &pack_list = m_sessionInfo[sessionId].packList;
	if (pack_list.size() > 0)
	{
        pack = pack_list[0];
        pack_list.pop_front();        
	}
    return pack;
}

int JZRpcDataManager::packCount(int sessionId)
{
    return m_sessionInfo[sessionId].packList.size();
}

void JZRpcDataManager::parsePack(int sessionId)
{
	QByteArray &buffer = m_sessionInfo[sessionId].buffer;	
    int buffer_start = 0;
	while (true)
	{
		int next = buffer.indexOf('\n', buffer_start);
        if(next < 0)
            break;

        QJsonParseError error;        
        QJsonDocument doc = QJsonDocument::fromJson(buffer.mid(buffer_start,next - buffer_start),&error);
		if(error.error == QJsonParseError::NoError)
        {
            m_sessionInfo[sessionId].packList.push_back(doc.object());
        }
        else
        {
            qDebug() << "unpack error";
        }

		//下一次读起始
		buffer_start = next + 1;
	}
	if(buffer_start != 0)
		buffer = buffer.mid(buffer_start);
}
